package org.jctc.els.modules.biz.controller.projects;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.pinyin.PinyinUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.AllArgsConstructor;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.jctc.els.common.config.BladeFileConfiguration;
import org.jctc.els.modules.biz.entity.projects.ElsProjectFiles;
import org.jctc.els.modules.biz.entity.projects.ElsProjectFilesCategory;
import org.jctc.els.modules.biz.service.projects.ElsProjectFilesCategoryService;
import org.jctc.els.modules.biz.service.projects.ElsProjectFilesService;
import org.jctc.els.modules.resource.builder.oss.OssBuilder;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.oss.model.BladeFile;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.tenant.annotation.NonDS;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.Func;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.List;

@Api(tags = "项目附件表对象功能接口")
@RestController
@AllArgsConstructor
@NonDS
@ApiIgnore
@MultipartConfig
@RequestMapping("/elsProjectFiles")
public class ElsProjectFilesController extends BladeController {

   @Autowired
   private ElsProjectFilesService elsProjectFilesService;

   @Autowired
   private ElsProjectFilesCategoryService categoryService;

    private BladeFileConfiguration bladeFileConfiguration;

    private final OssBuilder ossBuilder;



    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @ApiOperation("通过ID查询单条数据")
    @GetMapping("/detail")
    public R<ElsProjectFiles> getById(@RequestParam("id") Long id){
        ElsProjectFiles byId = elsProjectFilesService.getById(id);
        return R.data(byId);
    }

    @RequestMapping(value = "/listByProjectFiles")
    public R<List<ElsProjectFiles>> list(@RequestParam(value = "projectId") Long projectId) {
        List<ElsProjectFiles> lists = elsProjectFilesService.listByProjectFiles(projectId);
        return R.data(lists);
    }


    /**
     * 通过主键删除数据
     *
     * @param ids 主键
     * @return 是否成功
     */
    @ApiOperation("通过主键删除数据")
    @DeleteMapping("/remove")
    public R deleteById(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
        boolean delete = elsProjectFilesService.deleteLogic(Func.toLongList(ids));
        return R.status(delete);
    }

    /**
     * 上传
     *
     */
    @RequestMapping(value = "/uploadFile")
    public R uploadFile(final HttpServletRequest request, final HttpServletResponse response) {
        request.setAttribute("msg", "Not first time!");
        //创建一个“硬盘文件条目工厂”对象
        DiskFileItemFactory factory = new DiskFileItemFactory();
        //设置阈值，设置JVM一次能够处理的文件大小（默认吞吐量是10KB）
        factory.setSizeThreshold(DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD);
        //设置临时文件的存储位置（文件大小大于吞吐量的话就必须设置这个值，比如文件大小：1GB ，一次吞吐量：1MB）
        factory.setRepository(new File(bladeFileConfiguration.getUploadPath()));
        //创建核心对象
        ServletFileUpload fileUpload = new ServletFileUpload(factory);
        //设置最大可支持的文件大小（10MB）
        fileUpload.setFileSizeMax(1024 * 1024 * 50);
        //设置转换时使用的字符集
        fileUpload.setHeaderEncoding("UTF-8");
        String fileName = "";
        if (ServletFileUpload.isMultipartContent(request)) {
            try {
                List<FileItem> fileItems = fileUpload.parseRequest(request);
                for (FileItem fileItem : fileItems) {
                    if (fileItem.isFormField()) {//判断该FileItem为一个普通的form元素
                        //获取字段名
                        String fieldName = fileItem.getFieldName();
                        //获取字段值，并解决乱码
                        String fieldValue = fileItem.getString("UTF-8");
                        System.out.println(fieldName + " : " + fieldValue);

                    } else {//判断该FileItem为一个文件

                        String name = fileItem.getName();
                        System.out.println("Start to uplaod file!" + name);
                        //获取文件名
                        String name1 = PinyinUtil.getPinyin("n你好");
//                        fileName = PinyinUtil.getPinyin(name, "");
                        fileName = name;
                        System.out.println("fileName : " + fileName);
                        //获取文件大小
                        long fileSize = fileItem.getSize();
                        System.out.println("fileSize : " + fileSize);

                        fileItem.write(new File(bladeFileConfiguration.getUploadPath() + File.separator + fileName));

                    }
                }
            } catch (FileUploadException e) {
                e.printStackTrace();
                return R.status(false);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                return R.status(false);
            } catch (Exception e) {
                e.printStackTrace();
                return R.status(false);
            }
        }
        String path = File.separator + fileName;

        return R.data(path);
    }

    /**
     * 下载文件
     *
     * @param:
     * @return:
     * @author: ice.wang
     * @date: 2022/1/21
     */
    @RequestMapping("/download-index-file")
    public R downloadIndexFile(HttpServletResponse response,
                               @RequestParam("fileName") String fileName) throws Exception {
        QueryWrapper<ElsProjectFiles> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("fileName", fileName);
        //定义路径，下面会根据前端方法传的类型而进行判断，区分选择下载的模板，并给path赋值
		FileInputStream fis = new FileInputStream(bladeFileConfiguration.getUploadPath() + fileName);
        //创建文件对象，传递路径参数
        //File file = new File(path);

        //获取文件名
        //String filename1 = file.getName();

        //创建缓冲流
        // InputStream fis = new BufferedInputStream(new FileInputStream(path));
        byte[] buffer = new byte[fis.available()];
        //读操作
        fis.read(buffer);
        //关流
        fis.close();
        //设置响应信息 (响应编码等)
        response.reset();
        response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        //response.setHeader("Content-Disposition", "attachment;filename=" + new String("模板", "iso-8859-1"));
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        //响应输出流
        OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
        //写操作
        toClient.write(buffer);
        //刷新
        toClient.flush();
        //关流
        toClient.close();
        R.status(true);

        return R.status(false);
    }

    /**
     * 下载
     *
     */
    @RequestMapping("/download-file")
    public R downloadFile(HttpServletResponse response,
                          @RequestParam("id") Long id) throws Exception {
        QueryWrapper<ElsProjectFiles> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        ElsProjectFiles elsProjectFiles = elsProjectFilesService.getOne(queryWrapper);
        if (ObjectUtil.isNotEmpty(elsProjectFiles)) {
            //定义路径，下面会根据前端方法传的类型而进行判断，区分选择下载的模板，并给path赋值
            //String path = "src/main/resources/static/aaa.doc";
            // InputStream fis = TemplateStageController.class.getResourceAsStream("/static/aaa.doc");
            FileInputStream fis = new FileInputStream(bladeFileConfiguration.getUploadPath()+elsProjectFiles.getFileName());
            //创建文件对象，传递路径参数
            //File file = new File(path);

            //获取文件名
            //String filename1 = file.getName();

            //创建缓冲流
            // InputStream fis = new BufferedInputStream(new FileInputStream(path));
            byte[] buffer = new byte[fis.available()];
            //读操作
            fis.read(buffer);
            //关流
            fis.close();
            //设置响应信息 (响应编码等)
            response.reset();
            response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(elsProjectFiles.getFileName(), "UTF-8"));
            //response.setHeader("Content-Disposition", "attachment;filename=" + new String("模板", "iso-8859-1"));
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
            //响应输出流
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            //写操作
            toClient.write(buffer);
            //刷新
            toClient.flush();
            //关流
            toClient.close();
            R.status(true);
        }
        return R.status(false);
    }

    /**
     * 新增file
     */
    @PostMapping("/addCategory")
    @ApiOperation(value = "新增附件")
    public R addMaterial (@RequestBody ElsProjectFiles category) {
        BladeUser user = getUser();
        category.setDeptId(Long.valueOf(user.getDeptId()));
        return R.data(elsProjectFilesService.save(category));
    }

    @ApiOperation("查询list")
    @GetMapping("/listCategory")
    public R<List<ElsProjectFilesCategory>> queryList(@RequestParam("projectCategory") Integer projectCategory){
        return R.data(elsProjectFilesService.selectCateList(projectCategory));
    }
    /**
     * 查询Files
     */
    @GetMapping("/filesList")
    @ApiOperation("查询files")
    public R<List<ElsProjectFiles>> getFileList(@RequestParam("projectId") Long projectId,
                                                @RequestParam("categoryId") Long categoryId){
        return R.data(elsProjectFilesService.selectList(projectId,categoryId));
    }

    /*
    删除
     */
    @DeleteMapping("/delFile")
    @ApiOperation("删除附件")
    public R delFile(@RequestParam("id")Long id){
        Integer delete = elsProjectFilesService.delete(id);
        if (delete>0) {
            return R.status(true);
        }else{
            throw new RuntimeException("删除失败");
        }

    }

    /**
     *
     * @param request
     * @param projectCategory
     * @param projectType
     * @return
     */
    @PostMapping("project-material-file")
    @ApiOperation(value = "材料附件上传", notes = "传入pdf")
    public R importWorkersProjects(HttpServletRequest request, Integer projectCategory, Integer projectType) {
        String fileName = "";
        //创建一个“硬盘文件条目工厂”对象
        DiskFileItemFactory factory = new DiskFileItemFactory();
        //设置阈值，设置JVM一次能够处理的文件大小（默认吞吐量是10KB）
        factory.setSizeThreshold(DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD);
        //设置临时文件的存储位置（文件大小大于吞吐量的话就必须设置这个值，比如文件大小：1GB ，一次吞吐量：1MB）
        factory.setRepository(new File(bladeFileConfiguration.getUploadPath()));
        //创建核心对象
        ServletFileUpload fileUpload = new ServletFileUpload(factory);
        //设置最大可支持的文件大小（10MB）
        fileUpload.setFileSizeMax(1024 * 1024 * 50);
        Integer[] integers = null;
        //设置转换时使用的字符集
        fileUpload.setHeaderEncoding("UTF-8");
        if (ServletFileUpload.isMultipartContent(request)) {
            try {
                List<FileItem> fileItems = fileUpload.parseRequest(request);
                for (FileItem fileItem : fileItems) {
                    if (!(".pdf".equals(fileItem.getName().substring(fileItem.getName().lastIndexOf("."))))&&
                            !(".doc".equals(fileItem.getName().substring(fileItem.getName().lastIndexOf("."))))&&
                            !(".docx".equals(fileItem.getName().substring(fileItem.getName().lastIndexOf("."))))) {
                        throw new RuntimeException("请上传pdf/word文件");
                    }
                    if (fileItem.isFormField()) {//判断该FileItem为一个普通的form元素
                        //获取字段名
                        String fieldName = fileItem.getFieldName();
                        //获取字段值，并解决乱码
                        String fieldValue = fileItem.getString("UTF-8");
                        System.out.println(fieldName + " : " + fieldValue);

                    } else {//判断该FileItem为一个文件

                        //判断该FileItem为一个文件
                        String name = fileItem.getName();
                        System.out.println("Start to uplaod file!" + name);
                        //获取文件名
                        integers = NumberUtil.generateBySet(0, 99999999, 1);
                        String sub = name.substring(name.lastIndexOf(".") + 1);
                        fileName = integers[0] + "." + sub;
                        fileItem.write(new File(bladeFileConfiguration.getUploadPath() + File.separator + fileName));
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                return R.fail(e.getMessage());
            }
        }
        String path = File.separator + fileName;
        return R.data(path);
    }

    @ApiOperation("分页查询")
    @GetMapping("/category/page")
    public R<IPage<ElsProjectFilesCategory>> paginQuery(@RequestParam(value = "pageNum") Integer pageNum,
                                                        @RequestParam(value = "pageSize") Integer pageSize,
                                                        @RequestParam(value = "projectFilesCategoryName") String projectFilesCategoryName) {
        IPage<ElsProjectFilesCategory> elsProjectsPage = categoryService.paginQuery(pageNum, pageSize,projectFilesCategoryName);
        return R.data(elsProjectsPage);
    }

    @ApiOperation("新增类型")
    @PostMapping("/category/add")
    public R saveCategory(@RequestBody ElsProjectFilesCategory elsProjectFilesCategory) {
        elsProjectFilesCategory.setIsDelete(0);
        Boolean aBoolean = categoryService.insert(elsProjectFilesCategory) > 0;
        return R.data(aBoolean);
    }

    @ApiOperation("编辑类型")
    @PutMapping("/category/update")
    public R updateCategory(@RequestBody ElsProjectFilesCategory elsProjectFilesCategory) {
        Boolean aBoolean = categoryService.update(elsProjectFilesCategory);
        return R.data(aBoolean);
    }

}
